package io.gitee.baicaixiaozhan.httpmessagewrapper;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.gitee.baicaixiaozhan.httpmessagewrapper.kit.ServletResponseResultKit;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;

/**
 * DESC:
 *
 * @author baicaixiaozhan
 * @since v1.0.0
 */
public class HttpServletResponseResult implements UnifiedResult<Object> {

    @JsonIgnore
    private String code;

    @JsonIgnore
    private String status;

    @JsonIgnore
    private String message;

    @JsonIgnore
    private Object data;

    public HttpServletResponseResult() {}

    private HttpServletResponseResult(String code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    @Override
    public String getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public Object getData() {
        return data;
    }


    @Override
    public UnifiedResult<Object> ok() {
        addHeaders("200", HttpStatus.OK.getReasonPhrase(), HttpStatus.OK.value());
        return new HttpServletResponseResult("200", HttpStatus.OK.getReasonPhrase(), null);
    }

    @Override
    public UnifiedResult<Object> ok(Object data) {
        addHeaders("200", HttpStatus.OK.getReasonPhrase(), HttpStatus.OK.value());
        return new HttpServletResponseResult("200", HttpStatus.OK.getReasonPhrase(), data);
    }

    @Override
    public UnifiedResult<Object> fail(String code, String status, String message) {
        addHeaders(code, message, HttpStatus.valueOf(Integer.parseInt(status)).value());
        return new HttpServletResponseResult(code, message, null);
    }


    private static void addHeaders(String code, String message, int status) {
        HttpServletResponse response = ServletResponseResultKit.getHttpServletResponse();
        response.setStatus(status);
        response.addHeader("Server-Code", code);
        response.addHeader("Server-Message", message);
    }

}
